import Axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from "axios";
import { Toast } from "antd-mobile";
const service = Axios.create({
  baseURL: "http://leju.bufan.cloud/",
  timeout: 5000,
});

service.interceptors.request.use(
  (config: AxiosRequestConfig): any => {
    const token = localStorage.getItem("token") || "";
    Toast.show({
      icon: "loading",
      content: "加载中…",
    });
    return {
      ...config,
      headers: {
        "token": token, // 请求头中携带token信息
      },
    };
  },
  (err: AxiosError) => {
    Toast.clear()
    return Promise.reject(err.message);
  }
);

service.interceptors.response.use(
  (res: AxiosResponse) => {
    if (res.data.code === 20002) {
      Toast.show({
        icon: 'fail',
        content: res.data.message,
        duration: 800
      })
      return (() => {
        localStorage.clear()
        window.location.href = '/my/login'
      })()
    }
    Toast.clear();
    return res.data;
  },
  (err: AxiosError) => {
    Toast.clear();
    const { response } = err;
    // 处理 HTTP 网络错误
    let message = "";
    // HTTP 状态码
    const status = response?.status;
    switch (status) {
      case 401:
        message = "token 失效，请重新登录";
        // 这里可以触发退出的 action
        break;
      case 403:
        message = "拒绝访问";
        break;
      case 404:
        message = "请求地址错误";
        break;
      case 500:
        message = "服务器故障";
        break;
      default:
        message = "网络连接故障";
    }

    return Promise.reject(err);
  }
);
export default service;
